package de.cwach.svgeditor;

import java.awt.Dimension;
import java.io.File;
import java.util.LinkedList;

import javax.swing.JComponent;

import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.svg.SVGUserAgentAdapter;

public class SVGCanvas {

	/**
	 * SVGUserAgentAdapter for adaptable error handling.
	 * 
	 * @author wach
	 * 
	 */
	private class MySVGUserAgent extends SVGUserAgentAdapter {

		@Override
		public void displayError(Exception ex) {
			notifyErrorListener(ex.toString());
		}

		@Override
		public void displayError(String message) {
			notifyErrorListener(message);
		}

		@Override
		public void displayMessage(String message) {
			// do nothing!
		}
	}

	private LinkedList<ErrorListener> errorListeners;

	private JSVGCanvas canvas;

	public SVGCanvas() {
		canvas = new JSVGCanvas(new MySVGUserAgent(), false, false);
		canvas.setSize(new Dimension(512, 480));
		canvas.setFocusable(false);
		errorListeners = new LinkedList<ErrorListener>();
	}

	public void loadImage(File image) {
		canvas.setURI(image.toURI().toString());
	}

	public void addErrorListener(ErrorListener listener) {
		errorListeners.add(listener);
	}

	private void notifyErrorListener(String msg) {
		for (ErrorListener listener : errorListeners) {
			listener.notify(msg);
		}
	}

	public JComponent getSwingCanvas() {
		return canvas;
	}

}
